#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.abspath('../..'))
import time
import datetime
import camfwlib
import wave

if __name__ == '__main__':
    path = './images/'

    cf = camfwlib.camfwClient('172.16.80.30', 15680, './camfw.log', camfwlib.DEBUG) 

    cam_list = cf.get_cameralist()
    cf.log(camfwlib.DEBUG, 'returned camera id list : ' + ' '.join(cam_list))

    print "=== start streaming ==="
    termfrom = datetime.datetime.today()
    cf.start_audio_streaming('cam1')
    print "capturing..."
    time.sleep(10)
    termto = datetime.datetime.today()
    print "=== stop streaming ==="
    cf.stop_audio_streaming('cam1')

    """
    print "--- all ---"
    frames = cf.get_audio_imagelist('cam1')
    for frame in frames:
        print frame
    """

    print "--- range ---"
    tf_string = termfrom.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    tt_string = termto.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    frames = cf.get_audio_imagelist('cam1', [tf_string, tt_string])
    
    print "--- get_imagedata & save ---"
    buf = ''
    count = 0
    for frame in frames:
        framedata = cf.get_audio_imagedata(frame)
        print "%s len %d" % (frame, len(framedata))
        if framedata:
            buf += framedata
            count = count + 1

    w = wave.Wave_write(path + 'audio.wav')
    p = (1, 2, 8000, len(buf)/2, 'NONE', 'not compressed')
    w.setparams(p)
    w.writeframes(buf)
    w.close()
    print "total %d saved" % count

